/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.common.sign.controller;

import com.icinfo.cloud.provider.common.utils.FileUtil;
import com.icinfo.cloud.provider.punish.common.seal.utils.AuthToken;
import com.icinfo.cloud.provider.punish.common.seal.utils.ChongQingCenterSignUtil;
import com.icinfo.cloud.provider.common.dto.OcrData;
import com.icinfo.cloud.provider.punish.common.seal.utils.OcrUtil;
import com.icinfo.cloud.provider.punish.common.sign.dto.*;
import com.icinfo.cloud.provider.punish.common.sign.service.IFaduSignService;
import com.icinfo.cloud.provider.punish.common.sign.vo.SignSendFileVo;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceMaterialRecordService;
import com.icinfo.cloud.provider.punish.execute.dto.SignExecuteQueryDto;
import com.icinfo.cloud.provider.punish.execute.dto.SignExecuteReceiveDto;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteAppendixRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseConfirmPreviewDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseAppendixRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.web.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 签字确认公用controller
 *
 * @author 程亚运
 * @date 2022年02月15日
 */
@RestController
@RequestMapping("/sign")
@Slf4j
public class CommonSignController extends BaseController {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CommonSignController.class);

    @Autowired
    private ICaseDocumentRecordService caseDocumentRecordService;

    @Autowired
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Autowired
    private IExecuteAppendixRecordService executeAppendixRecordService;
    @Resource
    private ICaseSourceMaterialRecordService caseSourceMaterialRecordService;
    @Resource
    private IFaduSignService faduSignService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    /**
     *
     * ====================================================================签字确认=========================================================================
     *
     */

    /**
     * 上传线下已签署文书
     *
     * @param
     * @return
     */
    @PostMapping("/uploadOfflineSignDoc")
    public Result uploadOfflineSignDoc(@Validated @RequestBody SignReceiveDto signReceiveDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        // 前端直接调用文件服务上传
        // 接收文件地址
        // 保存入库
        if (caseAppendixRecordService.saveOfflineSignFile(signReceiveDto).size() > 1) {
            return Result.success("success");
        }
        return Result.error("fail");
    }

    /**
     * 上传线下已签署文书-案源
     *
     * @param signReceiveDto
     * @return {@link Result}
     * @author liyafeng
     * @date 2022/8/18
     */
    @PostMapping("/caseSource/uploadCSourceOfflineSignDoc")
    public Result uploadCaseSourceOfflineSignDoc(@Validated @RequestBody SignCaseSourceReceiveDto signReceiveDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        // 前端直接调用文件服务上传
        // 接收文件地址
        // 保存入库
        if (caseAppendixRecordService.saveOfflineSignFile(signReceiveDto) > 0) {
            return Result.success("success");
        }
        return Result.error("fail");
    }

    /**
     * 上传线下已签署文书-裁执分离
     *
     * @param signReceiveDto
     * @return {@link Result}
     * @author liyafeng
     * @date 2022/8/18
     */
    @PostMapping("/uploadExecuteOfflineSignDoc")
    public Result uploadExecuteOfflineSignDoc(@Validated @RequestBody SignExecuteReceiveDto signReceiveDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        // 前端直接调用文件服务上传
        // 接收文件地址
        // 保存入库
        if (executeAppendixRecordService.saveOfflineSignFile(signReceiveDto) > 0) {
            return Result.success("success");
        }
        return Result.error("fail");
    }

    /**
     * 接收捺印板回传已签字文书
     *
     * @param
     * @return
     */
    @PostMapping("/receiveSignDoc")
    public Result receiveSignDoc(@Validated @RequestBody SignReturnDto signReceiveDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        // 前端直接调用文件服务，将回传已签字文件上传返回地址，接收地址直接保存
        //保存到文书记录表
        Map<String, Object> result = caseDocumentRecordService.receiveSignDoc(signReceiveDto);
        if (result.size() > 1) {
            return Result.success("success");
        }
        return Result.error("fail");
    }

    /**
     * 接收捺印板回传已签字文书-案源
     *
     * @param signReceiveDto
     * @return {@link Result}
     * @author liyafeng
     * @date 2022/8/18
     */
    @PostMapping("/caseSource/receiveCSourceSignDoc")
    public Result receiveCaseSourceSignDoc(@Validated @RequestBody SignCaseSourceReturnDto signReceiveDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        // 前端直接调用文件服务，将回传已签字文件上传返回地址，接收地址直接保存
        //保存到文书记录表
        int num = caseDocumentRecordService.receiveSignDoc(signReceiveDto);
        if (num > 0) {
            return Result.success("success");
        }
        return Result.error("fail");
    }

    /**
     * 签字捺印版未签字原文件发送
     * 案件
     *
     * @param
     * @return
     */
    @PostMapping("/sendUnSignDoc")
    public Result<SignSendFileVo> sendUnSignDoc(@Validated @RequestBody SignQueryDto signQueryDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        //返回文件地址前端直接取
        return Result.success("success", caseDocumentRecordService.getUnSignDoc(signQueryDto));
    }

    /**
     * 签字捺印版未签字原文件发送-案源
     *
     * @param signQueryDto
     * @return {@link Result< SignSendFileVo>}
     * @author liyafeng
     * @date 2022/8/18
     */
    @PostMapping("/caseSource/sendCSourceUnSignDoc")
    public Result<SignSendFileVo> sendCaseSourceUnSignDoc(@Validated @RequestBody SignCaseSourceQueryDto signQueryDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        //返回文件地址前端直接取
        return Result.success("success", caseDocumentRecordService.getUnSignDoc(signQueryDto));
    }

    /**
     * 签字捺印版未签字原文件发送-裁执分离
     *
     * @param signQueryDto
     * @return {@link Result< SignSendFileVo>}
     * @author liyafeng
     * @date 2022/8/18
     */
    @PostMapping("/sendExecuteUnSignDoc")
    public Result<SignSendFileVo> sendExecuteUnSignDoc(@Validated @RequestBody SignExecuteQueryDto signQueryDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        //返回文件地址前端直接取
        return Result.success("success", caseDocumentRecordService.getExecuteUnSignDoc(signQueryDto));
    }


    /**
     * 接收签字捺印已签字文书---app 端
     *
     * @param
     * @return
     * @author lxj
     */
    @PostMapping("/receiveAppSignDoc")
    public Result receiveAppSignDoc(@Validated @RequestBody SignReturnDto signReceiveDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点。
        Map<String, Object> result = caseDocumentRecordService.receiveAppSignDoc(signReceiveDto);
        if (result.size() > 1) {
            return Result.success("success");
        }
        return Result.error("fail");
    }


    /**
     * 【V1.10.0】描述：APP端签字捺印案件流程滚动
     *
     * @param
     * @return
     * @author tianrunjia
     */
    @GetMapping("/doCaseRollByAppSignDoc")
    public Result doCaseRollByAppSignDoc(@RequestParam String caseId, @RequestParam String documentCatalogCode) {
        //现在不涉及多当事人的情况
        Map<String, Object> result = caseDocumentRecordService.doCaseRollByAppSignDoc(caseId, documentCatalogCode);
        if (result.size() > 1) {
            return Result.success("success");
        }
        return Result.error("fail");
    }


    /**
     * 接收海康捺印板回传已签字文书
     *
     * @param
     * @return
     */
    @PostMapping("/receiveHKSignDoc")
    public Result receiveHKSignDoc(@Validated @RequestBody SignSaveDto SignSaveDto) {
        Map<String, Object> result = caseDocumentRecordService.receiveHKSignDoc(SignSaveDto);
        if (result.size() > 1) {
            return Result.success("success");
        }
        return Result.error("fail");
    }


    /**
     * 保存海康捺印板回传的签字文书
     *
     * @param saveDto 保存dto
     * @return {@link Result }
     * @author shishengyao
     * @date 2022/10/26
     */
    @PostMapping("/saveSignAttachmentFile")
    public Result saveSignAttachmentFile(@Validated @RequestBody SignAttachmentFileSaveDto saveDto) {
        int result = caseAppendixRecordService.saveSignAttachmentFile(saveDto);
        if (result > 0) {
            return Result.success("保存成功");
        }
        return Result.error("保存失败");
    }

    /**
     * 接收海康签字捺印办附件
     *
     * @param
     * @return
     */
    @PostMapping("/saveCSourceSignAttachmentFile")
    public Result saveCSourceSignAttachmentFile(@Validated @RequestBody SignAttachmentFileCSourceSaveDto SignSaveDto) {
        int result = caseSourceMaterialRecordService.saveSignAttachmentFile(SignSaveDto);
        if (result > 0) {
            return Result.success("success");
        }
        return Result.error("fail");
    }

    /**
     * 接收海康签字捺印办附件
     *
     * @param
     * @return
     */
    @PostMapping("/getSignZipDemo")
    public Result getSignZipDemo(String requestId) {
        faduSignService.getSignZipDemo(requestId);
        return Result.error("fail");
    }

    /**
     * 描述: 浙里办送达地址确认书预览文书
     *
     * @param caseConfirmPreviewDto
     * @return com.icinfo.framework.common.web.Result
     * @author zhanghongqiang
     * @Date 2022/12/7
     */
    @PostMapping(value = "/zlbCaseConfirmPreview")
    public Result<Map<String, Object>> readZlbCaseConfirmPreview(@RequestBody @Validated CaseConfirmPreviewDto caseConfirmPreviewDto) {
        Map<String, Object> map = caseDocumentRecordService.getZlbCaseConfirmPreview(caseConfirmPreviewDto);
        return Result.success(map);
    }

    /**
     * 描述: 浙里办送达地址确认书修改再提交
     * todo 可能不太需要
     * @param caseConfirmPreviewDto
     * @return com.icinfo.framework.common.web.Result
     * @author zhanghongqiang
     * @Date 2022/12/8
     */
/*    @PostMapping(value = "/editZlbCaseConfirm")
    public Result<String> editZlbCaseConfirm(@RequestBody @Validated CaseConfirmPreviewDto caseConfirmPreviewDto) {
        return caseDocumentRecordService.modZlbCaseConfirm(caseConfirmPreviewDto);
    }*/

    /**
     * 描述: 当前文书发送到浙里办签字确认
     *
     * @param saveDto
     * @return com.icinfo.framework.common.web.Result<java.util.Map < java.lang.String, java.lang.Object>>
     * @author zhanghongqiang
     * @Date 2022/12/8
     */
    @PostMapping(value = "/sendZlbSignDoc")
    public Result<String> sendZlbSignDoc(@RequestBody @Validated sendSignDocZlbDto saveDto) {
        int count = caseDocumentRecordService.sendZlbSignDoc(saveDto);
        if (count > 0) {
            return Result.success("发送成功!");
        } else {
            return Result.success("发送失败!");
        }
    }

    /**
     * 描述: 浙里办签字完成调取接口，需要签字的文书通用
     *
     * @param saveDto
     * @return com.icinfo.framework.common.web.Result
     * @author zhanghongqiang
     * @Date 2022/12/7
     */
    @PostMapping(value = "/receiveZlbSignDoc")
    public Result<Map<String, Object>> receiveZlbSignDoc(@RequestBody @Validated SignReturnDto saveDto) {
        Map<String, Object> map = caseDocumentRecordService.receiveZlbSignDoc(saveDto);
        return Result.success(map);
    }

    /**
     * 根据重庆的文件id来下载文件
     *
     * @param fileId
     * @return
     */
    @GetMapping("/getFileByteByFileId")
    public Result<byte[]> getFileByteByFileId(@RequestParam String fileId) {
        byte[] fileBytes = ChongQingCenterSignUtil.downLoad(fileId);
//        String base64 = Base64.encodeBase64String(fileBytes);
        return Result.success(fileBytes);
    }

    /**
     * 更新ocrtoken
     *
     * @param ocrToken
     * @return
     */
    @PostMapping("/setOcrToken")
    public Result<String> getOcrData(String  ocrToken) {
        redisTemplate.opsForValue().set("ocr_token",ocrToken);
        return Result.success("更新成功");
    }

    /**
     * 获取ocr文字, app 会使用
     *
     * @param file
     * @return
     */
    @PostMapping("/getOcrData")
    public Result<List<OcrData>> getOcrData(@RequestParam("file") MultipartFile file) {
        File oriFile = null;
        try {
            oriFile = FileUtil.multipartFileToFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        String ocrToken = redisTemplate.opsForValue().get("ocr_token");
//        logger.info("ocrToken:{}",ocrToken);
        List<OcrData> data = OcrUtil.getOcrData(oriFile);
        return Result.success(data);
    }

    /**
     * 重庆接口token app 会使用
     *
     * @return
     */
    @GetMapping("/getToken")
    public Result<String> getToken() {
        AuthToken authToken = ChongQingCenterSignUtil.getAuthToken();
        return Result.success("获取成功", authToken.getAccessToken());
    }
}
